package sunyu.shiro.filter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import sunyu.config.Constant;
import sunyu.pojo.ShiroResource;
import sunyu.service.ResourceService;
import sunyu.toolkit.SpringKit;
import sunyu.toolkit.core.LogKit;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 孙宇
 */
public class MyFilter implements Filter {

    private static final Logger logger = LogKit.getLogger();

    ResourceService resourceService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Subject subject = SecurityUtils.getSubject();


        String url = ((HttpServletRequest) servletRequest).getServletPath();
        logger.debug("访问的路径是 {}", url);

        if (resourceService == null) {
            resourceService = (ResourceService) SpringKit.getBean("resourceService");
        }

        Map params = new HashMap<>();
        params.put("url_isNotNull", "isNotNull");
        params.put("permission_isNotNull", "isNotNull");
        for (ShiroResource r : resourceService.select(params)) {
            if (r.getUrl().equals(url)) {//如果当前访问的路径，是需要权限验证的路径
                if (subject.isAuthenticated() && subject.getPrincipals() != null) {//判断是否是登录状态
                    if (subject.isPermitted(r.getPermission())) {//判断是否有权限
                        filterChain.doFilter(servletRequest, servletResponse);
                        return;
                    } else {
                        servletRequest.getRequestDispatcher(Constant.unauthorizedUrl).forward(servletRequest, servletResponse);
                        return;
                    }
                } else {
                    servletRequest.getRequestDispatcher(Constant.noLoginUrl).forward(servletRequest, servletResponse);
                    return;
                }
            }
        }

        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }

    @Override
    public void destroy() {
    }
}
